package tgc.edu.fhh.service;



import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.fhh.custom.BaseService;
import tgc.edu.fhh.entity.Student;
import tgc.edu.fhh.entity.SysRole;
import tgc.edu.fhh.entity.TbClass;
import tgc.edu.fhh.repository.StudentRepository;
import tgc.edu.fhh.web.form.StudentForm;
@Service
public class StudentService extends BaseService<Student, Integer>{
	@Autowired
	private StudentRepository studao;
	@Value("${web.file-path}")
	private String path;
	@Autowired
	private SysRoleService sysService;
	@Autowired
	private TbClassService tbService;

	public List<Student> findBytbclassId(Integer bjId) {
		return studao.findBytbclassId(bjId);
	}

	@Transactional
	public synchronized Boolean save(StudentForm form) {
		try {
			BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
			Integer id = form.getId();
			MultipartFile file = form.getFile();
			Student model=new Student();
			if(id!=null) {
				model=findById(id);
			}else {
				model.setPassword(encoder.encode("1234"));
				SysRole role = sysService.findById(2);
				List<SysRole> roles = new ArrayList<SysRole>();
				roles.add(role);
				model.setRoles(roles);
				Integer bjId = form.getTbclassId();
				TbClass tbClass = tbService.findById(bjId);
				model.setTbclass(tbClass);
			}
			
			if(file!=null) {
				String originalFilename = file.getOriginalFilename();
				if(StringUtils.hasText(originalFilename)) {
					String uuid = model.getUuid();
					if(uuid!=null) {
						File f=new File(path,uuid);
						f.delete();
					}
					uuid=UUID.randomUUID().toString();
					model.setUuid(uuid);
					model.setFilename(originalFilename);
					File f=new File(path, uuid);
					file.transferTo(f);
				}
			}
			BeanUtils.copyProperties(form, model,"id");
			save(model);
			return true;
		} catch (Exception e) {
			return false;
		}
		
	}

}
